package lib

import (
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	"time"
)

type STime struct {
	// 爸爸的事情我全部拿过来了
	time.Time
}

var (
	DATETIME_FORMAT_PATTERN = "2006-01-02 15:04:05"
	DATE_FORMAT_PATTERN     = "2006-01-02"
)

/**
 * @author feige
 * @date 2023-10-15
 * @version 1.0
 * @desc json序列化
 */
func (t STime) MarshalJSON() ([]byte, error) {
	if t.IsZero() {
		return []byte("\"\""), nil
	}
	stamp := fmt.Sprintf("\"%s\"", t.Format(DATETIME_FORMAT_PATTERN))
	return []byte(stamp), nil
}

/**
 * @author feige
 * @date 2023-10-15
 * @version 1.0
 * @desc  json反序列化
 */
func (t *STime) UnmarshalJSON(data []byte) error {
	var err error
	t.Time, err = time.Parse(`"`+DATETIME_FORMAT_PATTERN+`"`, string(data))
	if err != nil {
		t.Time, err = time.Parse(`"`+DATE_FORMAT_PATTERN+`"`, string(data))
	}
	return err
}

/**
 * @author feige
 * @date 2023-10-15
 * @version 1.0
 * @desc 快速打印的日期信息
 */
func (t *STime) String() string {
	data, _ := json.Marshal(t)
	return string(data)
}

// FieldType 数据类型
func (t *STime) FieldType() int {
	return orm.TypeDateTimeField
}

// SetRaw 读取数据库值 --- select
func (t *STime) SetRaw(value interface{}) error {
	t.Time, _ = time.Parse(`"`+DATETIME_FORMAT_PATTERN+`"`, string(value.([]uint8)))
	return nil
}

// RawValue 写入数据库---insert/update
func (t *STime) RawValue() interface{} {
	return t.Time
}
